<template>
    <div class="production-plan">
      <el-button type="primary" @click="saveAll">保存主表单和明细</el-button>
      <h3 class="title">调拨申请</h3>
      
      <!-- 基本信息 -->
      <el-form ref="formRef" :model="formData" :rules="rules" label-position="right" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据主题">
              <el-input v-model="formData.documentSubject" placeholder="请输入主题" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据编号">
              <el-input v-model="formData.documentNumber" placeholder="请输入编号" disabled />
            </el-form-item>
          </el-col>

          <!-- 库管人员显示 -->
            <el-col :span="6">
                <el-form-item label="审核人员" >
                <el-input 
                placeholder="请输入" 
                v-model="formData.auditor" 
                required
              >
                <template #suffix>
                  <el-button size="mini" @click="openAssociatedItemDialog">
                    <i class="el-icon-search"></i>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            </el-col>
            <el-col :span="6">
            <el-form-item label="申请人员">
              <el-input v-model="formData.applican" placeholder="请输入备注" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="*申请时间" prop="pickingDate">
              <el-date-picker
                v-model="formData.applicationTime"
                type="date"
                required
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关联项目">
              <el-input v-model="formData.relatedProject" placeholder="请输入"  disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
          <el-form-item label="调拨备注">
              <el-input v-model="formData.transferRemark" placeholder="请填写" />
          </el-form-item>
          </el-col>
        </el-row>  

      </el-form>

      <!-- 调拨明细明细 -->
      <div class="detail-section">
        <h4 class="sub-title">出库明细</h4>
        <el-button size="small" @click="addNewRow">新增行</el-button>
        <el-table :data="planDetailsList" border style="width: 100%">
          <el-table-column label="产品名称" width="180px">
            <template #default="{ row }">
              <el-input 
                v-model="row.productName" 
                :readonly="row.isSaved"
              >
                <template #suffix>
                  <el-button size="mini"   @click="openProductNameDialog(row)">
                    <i class="el-icon-search"></i>
                    <el-icon><Search /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </template>
          </el-table-column>
  
          <el-table-column label="产品编号">
            <template #default="{ row }">
              <el-input v-model="row.productCode" :readonly="row.isSaved"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="规格型号">
            <template #default="{ row }">
              <el-input v-model="row.specificationModel" :readonly="row.isSaved"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="单位">
            <template #default="{ row }">
              <el-input v-model="row.unit" :readonly="row.isSaved"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="申请数量">
            <template #default="{ row }">
              <el-input-number 
                v-model.number="row.applicationQuantity" 
                :min="0" 
                controls-position="right"
                :disabled="row.isSaved"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="备注">
            <template #default="{ row }">
              <el-input v-model="row.detailRemark" type="textarea" rows="3" :readonly="row.isSaved"></el-input>
            </template>
          </el-table-column>
         <el-table-column fixed="right"  label="操作" width="180px">
            <template #default="{ row }">
              <!-- 移除单独保存明细按钮 -->
              <el-button size="small"  type="danger" @click="deleteDetail(row)" :disabled="row.isSaved">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
  
     <!-- 附件部分 -->
          <div class="attachment-section">
              <h4 class="sub-title">附件管理</h4>
              <el-button size="small" @click="batchUpload">批量上传</el-button>
              <el-table :data="attachments" border style="width: 100%">
                  <el-table-column label="文件名称" prop="fileName"></el-table-column>
                  <el-table-column label="文件大小" prop="fileSize"></el-table-column>
                  <el-table-column label="上传人" prop="uploader"></el-table-column>
                  <el-table-column label="上传时间" prop="uploadTime"></el-table-column>
              </el-table>
          </div>
  
  
  
  
           <!--物流管理产品名称选择对话框 -->
      <el-dialog
        v-model="associatedItemDialogVisible"
        width="500px"
        title="关联项目选择"
        append-to-body
      >
        <el-table
          :data="associatedItems"
          highlight-current-row
          border
          size="small"
          @current-change="handleAssociatedItemChange"
        >
          <el-table-column type="index" label="序号" />
          <el-table-column property="productsNumber" label="产品编号" />
          <el-table-column property="productsName" label="产品名称" />
          <el-table-column property="productsNum" label="规格型号" />
          <el-table-column property="productsUnit" label="单位" />
        </el-table>
        <template #footer>
          <el-button @click="pickAssociatedItem">确定</el-button>
        </template>
      </el-dialog>
  
       <!-- 物理明细产品名称选择对话框 -->
      <el-dialog
        v-model="productNameDialogVisible"
        width="500px"
        title="产品名称选择"
        append-to-body
      >
        <el-table
          :data="productNames"
          highlight-current-row
          border
          size="small"
          @current-change="handleProductNameChange"
        >
          <el-table-column type="index" label="序号" />
          <el-table-column property="productsNumber" label="产品编号" />
          <el-table-column property="productsName" label="产品名称" />
          <el-table-column property="productsNum" label="规格型号" />
          <el-table-column property="productsUnit" label="单位" />
        </el-table>
        <template #footer>
          <el-button @click="pickProductName">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  
  import axios from 'axios';
  import { Materialread, Materialwrite } from '@/axios/axiosHelper';
  const formRef = ref(null);
  const currentUser = ref("admin"); 
  const router = useRouter();
  const route = useRoute();
  
  // 主表单数据
  const formData = reactive({
   "allocateId": 0,
  "documentSubject": "",
  "documentNumber": "",
  "auditor": "",
  "applican": currentUser.value,
  "applicationTime": new Date().toISOString(),
  "relatedProject": "",
  "transferRemark": "",
  "isDel": true
  });
  
  // 主表单验证规则
  
  const rules = reactive({
    bomSubject: [
      { required: true, message: '不能为空', trigger: 'blur' }
    ],
    productName: [
      { required: true, message: '不能为空', trigger: 'blur' }
    ],
    documentNo: [
      { required: true, message: '不能为空', trigger: 'blur' }
    ],
  
  });
  
  
  // 明细数据列表
  const planDetailsList = ref([]);
  
  const attachments = ref([]);
  
  // 监听路由参数变化
  watch(() => route.query, async (newQuery) => {
      if (newQuery.allocateId) {
          await getProductionById(newQuery.allocateId);
      } else {
          // 清空表单
          formData.documentSubject = "";
          formData.documentNumber = "";
          formData.applican = currentUser.value;
          formData.auditor = "";
          formData.creationTime = new Date().toISOString();
          formData.relatedProject = "";
          formData.transferRemark = "";
          formData.allocateId = null;
          planDetailsList.value = [];
      }mainData
  });
  
  const getProductionById = async (allocateId) => {
      try {
          const [mainResponse, detailResponse] = await Promise.all([
          axios.get('https://localhost:7090/api/Allocateee/FTAllocate', {
                  params: { AllocateId: allocateId }
              }),
              axios.get('https://localhost:7090/api/Allocateee/FTAllocationDetails', {
                  params: { AllocationDetailsId: allocateId }
              })
          ]);
  
          if (mainResponse.data.code === 200) {
              const mainData = mainResponse.data.data[0];
              formData.documentSubject = mainData.documentSubject;
              formData.documentNumber = mainData.documentNumber;    
              formData.auditor = mainData.auditor;
              formData.applican = mainData.applican;
              formData.applicationTime = mainData.applicationTime;
              formData.relatedProject = mainData.relatedProject;
              formData.transferRemark = mainData.transferRemark;
              formData.allocateId = mainData.allocateId;
          }
          if (detailResponse.data.code === 200) {
              planDetailsList.value = detailResponse.data.data.map(item => ({
                allocationDetailsId: item.allocationDetailsId || '',
                productName: item.productName || "",
                productCode: item.productCode || "",
                specificationModel: item.specificationModel || "",
                unit: item.unit || "",
                applicationQuantity: item.applicationQuantity || 0,
                detailRemark: item.detailRemark || 0,
                allocateId: item.allocateId || null, 
                }));
          }
      } catch (error) {
          console.error('查询失败:', error);
          ElMessage.error('数据加载失败，请检查网络或联系管理员');
      }
  };
  
  
  
  // 保存主表单和明细
  const saveAll = async () => {
    if (formRef.value) {
      const isValid = await formRef.value.validate();
      if (isValid) {
        try {
          // 保存主表单
          const response = await axios.put('https://localhost:7279/api/Allocate/UpdateAllocate', formData);
          if (response.data.code === 400) {
            formData.allocateId = response.data.data.allocateId;
            ElMessage.success('主表单保存成功');
            router.push('/ShoAllocate');
            // 保存明细
            const saveDetailPromises = planDetailsList.value.map(async (row) => {
              const detailWithId = {
                ...row,
                allocationDetailsId: formData.allocateId
              };
              const detailResponse = await axios.put(
                'https://localhost:7279/api/Allocate/UpdateAllocationDetails',
                detailWithId
              );
              if (detailResponse.data.code === 400) {
                row.isSaved = true;
                return true;
              } else {
                ElMessage.error(`明细保存失败：${detailResponse.data.message}`);
                return false;
              }
            });
  
            const results = await Promise.all(saveDetailPromises);
            if (results.every(result => result)) {
              ElMessage.success('所有明细保存成功');
              router.push('/ShoAllocate');
            }
          } else {
            ElMessage.error(`主表单保存失败：${response.data.message}`);
          }
        } catch (error) {
          // console.error('保存过程中发生错误:', error.response?.data);
          // ElMessage.error('保存过程中发生错误，请检查网络或联系管理员');
        }
      }
    }
  };
  
  
  // // 保存主表单
  // const addjihau = async () => {
  //     try {
  //         const response = await axios.put('https://localhost:7077/api/Ment/UpdateMaterials', formData);
  //         if (response.data.code === 400) {
  //             formData.bomid = response.data.data.bomid;
  //             ElMessage.success('主表单保存成功');
  //         } else {
  //             ElMessage.error(`主表单保存失败：${response.data.message}`);
  //         }
  //     } catch (error) {
  //         console.error('保存错误:', error);
  //         ElMessage.error('保存失败，请检查网络或联系管理员');
  //     }
  // };
  // 新增行
  const addNewRow = () => {
      planDetailsList.value.push({
       "allocationDetailsId": '',
        "productName": "",
        "productCode": "",
        "specificationModel": "",
        "unit": "",
        "applicationQuantity": '',
        "detailRemark": "",
        "allocateId": null,
        "isDel": true,
      });
  };
  
  // 批量保存明细
//   const batchSaveDetails = async () => {
//       if (!formData.bomid) {
//           ElMessage.warning('请先保存主表单');
//           return;
//       }
  
//       const detailsWithId = planDetailsList.value.map(detail => ({
//           ...detail,
//           bomid: formData.bomid
//       }));
  
//       try {
//           const response = await Materialwrite.post(
//               '/l-wirth/api/Ment/PLAddMaterials',
//               detailsWithId
//           );
//           if (response.data.code === 400) {
//               // 更新 planDetailsList 中的 productionScheduleDetailId
//               planDetailsList.value = response.data.data.map((item, index) => ({
//                   ...planDetailsList.value[index],
//                   childID: item.childID
//               }));
//               ElMessage.success('明细批量保存成功');
//           } else {
//               ElMessage.error(`明细批量保存失败：${response.data.message}`);
//           }
//       } catch (error) {
//           console.error('保存错误:', error);
//           ElMessage.error('保存失败，请检查网络或联系管理员');
//       }
//   };
  
//   // 修改单条明细
//   const UpdateDetail = async (row) => {
      // if (!formData.bomid) {
      //     ElMessage.warning('请先保存主表单');
      //     return;
      // }
  
      // const detailData = {
      //     ...row,
      //     bomid: formData.bomid
      // };
  
      // console.log('发送给后端的明细数据:', detailData); // 打印发送给后端的数据
  
    //   try {
    //       const response = await axios.put(
    //           'https://localhost:7077/api/Ment/UpdateMaterialsChild',
    //           detailData
    //       );
    //       // console.log('后端返回的响应:', response); // 打印后端返回的响应
  
    //       if (response.data.code === 400) {
    //           ElMessage.success('明细更新成功');
    //       } else {
    //           ElMessage.error(`更新失败：${response.data.message}`);
    //       }
    //   } catch (error) {
    //       console.error('更新错误:', error);
    //       ElMessage.error('更新失败，请检查网络或联系管理员');
    //   }
//   };
  
  // 删除单条记录
  const deleteDetail = async (allocateId) => {
      try {
          const confirmResult = await ElMessageBox.confirm(
              '确认删除该条记录？',
              '提示',
              {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
              }
          );
          if (confirmResult === 'confirm') {
              const response = await axios.delete(
                  `https://localhost:7077/api/Ment/DelMaterials`,
                  {
                      params: { allocateId: allocateId.toString() }
                  }
              );
              if (response.data.code === 300) {
                  ElMessage.success('删除成功');
                  ShowMaterials(); // 调用 ShowMaterials 方法刷新数据
              } else {
                  ElMessage.error(`删除失败：${response.data.message}`);
              }
          }
      } catch (error) {
          if (error !== 'cancel') {
              console.error('删除错误:', error);
              ElMessage.error('删除失败，请检查网络或联系管理员');
          }
      }
  };
  // 产品名称数据
  const productNames = ref([]);
  
  const productNameDialogVisible = ref(false);
  const currentProductNameRow = ref(null);
  const currentProductName = ref({});
  
  // 获取产品信息
  const fetchProducts = () => {
    axios.get("https://localhost:7095/api/Products/GetProducts")
      .then(res => {
        productNames.value = res.data.data;
        console.log("产品数据：", productNames.value);
        nextTick(() => {
          // 强制更新表格
        });
      })
      // .catch(error => {
      //   console.error('获取产品信息失败:', error);
      //   ElMessage.error('获取产品信息失败，请检查网络或联系管理员');
      // });
  };
  
  
  
  // 打开产品名称选择对话框
  const openProductNameDialog = (row) => {
    if (productNames.value.length === 0) {
      ElMessage.warning('产品信息正在加载，请稍后重试');
      return;
    }
    currentProductNameRow.value = row;
    productNameDialogVisible.value = true;
  };
  
  // 当前选中的产品名称行
  const handleProductNameChange = (val) => {
    currentProductName.value = val;
  };
  
  // 选择产品名称
  const pickProductName = () => {
    if (currentProductName.value && currentProductNameRow.value) {
      currentProductNameRow.value.productNamess = currentProductName.value.productsName;
      currentProductNameRow.value.productCodess = currentProductName.value.productsNumber;
      currentProductNameRow.value.specificationModelss = currentProductName.value.productsNum;
      currentProductNameRow.value.unitss = currentProductName.value.productsUnit;
      currentProductNameRow.value.productInfoFilled = true; // 设置标志位，表示产品信息已填充
      productNameDialogVisible.value = false;
    }
  };
  
  // 对话框显示状态
  const associatedItemDialogVisible = ref(false);
  const currentAssociatedItem = ref({});
  // 关联项目数据
  const associatedItems = ref([]);
  // 打开关联项目选择对话框
  const openAssociatedItemDialog = () => {
    associatedItemDialogVisible.value = true;
  };
  // 当前选中的关联项目行
  const handleAssociatedItemChange = (val) => {
    currentAssociatedItem.value = val;
  };
  // 选择关联项目
  const pickAssociatedItem = () => {
    if (currentAssociatedItem.value) {
      formData.productName = currentAssociatedItem.value.productsName; // 产品名称
      formData.productCode = currentAssociatedItem.value.productsNumber; // 产品编号
      formData.specificationModel = currentAssociatedItem.value.productsNum; // 规格型号
      formData.unit = currentAssociatedItem.value.productsUnit; // 单位
      associatedItemDialogVisible.value = false;
    }
  };
  // 获取关联项目数据
  const fetchAssociatedProjects = () => {
    axios.get("https://localhost:7095/api/Products/GetProducts")
      .then(res => {
        associatedItems.value = res.data.data;
  
      })
      // .catch(error => {
      //   console.error('获取产品信息失败:', error);
      //   ElMessage.error('获取产品信息失败，请检查网络或联系管理员');
      // });
  };
  onMounted(() => {
      if (route.query.allocateId) {
          getProductionById(route.query.allocateId);
      }   
    fetchProducts();
  
  });
  </script>
  
  <style scoped>
  .production-plan {
      padding: 20px;
  }
  
  .title {
      text-align: center;
      margin-bottom: 20px;
  }
  
  .sub-title {
      margin: 20px 0 10px;
      font-size: 16px;
      font-weight: 500;
  }
  
  .detail-section,
  .attachment-section {
      margin-top: 20px;
  }
  
  .el-table {
      margin-top: 10px;
  }
  </style>    